package com.king.wxpay.util;

import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;

import java.io.FileInputStream;
import java.security.KeyStore;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 证书授权工具类
 * @author taomk
 * @version 1.0
 * @since 15-7-10 下午4:08
 */
public class KeyTool {
	private static Logger logger=Logger.getLogger(KeyTool.class.getName());
	
    public static KeyStore getKeyStore(String password, String keyStorePath, String type) throws Exception {  
        KeyStore ks = KeyStore.getInstance(type);// JKS
        FileInputStream is = new FileInputStream(keyStorePath);  
        ks.load(is, password.toCharArray());
        is.close();
        return ks;  
    }  

    public static KeyManager[] getKeyManagers(String password,String ksfile,String kstype){
    	try{
	        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());  
	        KeyStore keyStore = getKeyStore(password,ksfile,kstype);
	        keyManagerFactory.init(keyStore, password.toCharArray());
	        return keyManagerFactory.getKeyManagers();
    	}catch(Exception e){
    		logger.log(Level.WARNING,"getKeyManagers",e);
    	}
    	return null;
    }
    
    public static TrustManager[] getTrustManagers(String password,String ksfile,String kstype){
    	try{
            TrustManagerFactory trustManagerFactory=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());  
            KeyStore trustStore = getKeyStore(password, ksfile,kstype);  
            trustManagerFactory.init(trustStore);
	        return trustManagerFactory.getTrustManagers();
    	}catch(Exception e){
    		logger.log(Level.WARNING,"getKeyManagers",e);
    	}
    	return null;
    }
}
